/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package zerocopy_client;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 *
 * @author Teva
 */
public class ZeroCopy_Client {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException 
    {
            //String host = "10.141.11.191";
            
	    //int port = 3689;           //9026;
            
            String host = "localhost";
                    
            int port = 5000;
                                  
	    SocketAddress sad = new InetSocketAddress(host, port);
            
	    SocketChannel sc = SocketChannel.open();
            
	    sc.connect(sad);
            
	    sc.configureBlocking(true);

	   File file = new File("C:/JavaExample/file8.txt");
                          
           long start = System.currentTimeMillis();
            
           ZeroCopy_Client.fileTransfer(file, sc);
       
           System.out.println("Total time taken in MS--"+(System.currentTimeMillis() - start));
    }
    
     public static void fileTransfer(File in, SocketChannel sc) throws IOException 
    {
        
    FileChannel inChannel = new FileInputStream(in).getChannel();
      
    try 
    {
        // inChannel.transferTo(0, inChannel.size(), outChannel); // original -- apparently has trouble copying large files on Windows
        // magic number for Windows, (64Mb - 32Kb)
        //int maxCount = (64 * 1024 * 1024) - (32 * 1024);
        int maxCount = 4 * 64 * 1024;
        long size = inChannel.size();
        long position = 0;
        
        while (position < size) 
        {
             position += inChannel.transferTo(position, maxCount, sc);       
          
        }
    } 
    finally {
        if (inChannel != null) 
        {
            inChannel.close();
        }        
    }
  }
}
